package com.orange.framework.interceptor;

import com.orange.common.annotation.PassToken;
import com.orange.common.base.entity.TokenInfo;
import com.orange.common.base.redis.utils.RedisCache;
import com.orange.common.constant.HeaderConstants;
import com.orange.common.enums.ResultCodeEnum;
import com.orange.common.exception.BusinessException;
import com.orange.common.utils.StringUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;

/**
 * TODO
 *
 * @Author YWF
 * @Date 2022/1/24 17:46
 */
public class TokenInterceptor implements HandlerInterceptor {

    private final static Logger logger = LoggerFactory.getLogger(TokenInterceptor.class);

    @Autowired
    private RedisCache redisCache;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler){
        logger.info("==========================Token拦截器开始执行===================================");
        if (handler instanceof HandlerMethod){
            final HandlerMethod handlerMethod = (HandlerMethod) handler;
            final Class<?> clazz = handlerMethod.getBeanType();
            final Method method = handlerMethod.getMethod();
            if (clazz.isAnnotationPresent(PassToken.class) || method.isAnnotationPresent(PassToken.class)){
                logger.info("==========================不强制要求携带Token===================================");
                String token = request.getHeader(HeaderConstants.X_TOKEN);
                //校验token是否存在，存在，则判断token是否合法
                if (StringUtil.isNotEmpty(token)){
                    //校验token
                    this.isValidateToken(request);
                }
            }else{
                //校验token
                this.isValidateToken(request);
            }
        }
        return true;
    }


    private void isValidateToken(HttpServletRequest request){
        /*获取请求头Token*/
        String token = request.getHeader(HeaderConstants.X_TOKEN);
        /*判断请求头Token是否存在*/
        if (StringUtil.isEmpty(token)){
            throw new BusinessException(ResultCodeEnum.TOKEN_PARAM_IS_EMPTY);
        }
        // 3. 校验Token是否存在
        TokenInfo tokenInfo = redisCache.get(token);
        if (tokenInfo==null){
            throw new BusinessException(ResultCodeEnum.TOKEN_ERROR);
        }
    }



}
